﻿using System;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Threading.Tasks;
using YiSha.Util;
using YiSha.Util.Extension;
using YiSha.Util.Model;
using YiSha.Data;
using YiSha.Data.Repository;
using YiSha.Entity.QixingManage;
using YiSha.Model.Param.QixingManage;
using YiSha.Enum.QixingManage;
using YiSha.Model.Result.QixingManage;

namespace YiSha.Service.QixingManage
{
    /// <summary>
    /// 创 建：admin
    /// 日 期：2023-03-19 19:43
    /// 描 述：商品规格库存表服务类
    /// </summary>
    public class GoodsWarehouseService :  RepositoryFactory
    {
        //private GoodsStorageRecordService goodsStorageRecordService = new GoodsStorageRecordService();
        #region 获取数据
        public async Task<List<GoodsWarehouseEntity>> GetList(GoodsWarehouseListParam param)
        {
            var expression = ListFilter(param);
            var list = await this.BaseRepository().FindList(expression);
            return list.ToList();
        }

        
        public List<goodscar> GetSelectCarListJson(GoodsWarehouseListParam param)
        {
            var expression = ListFilter(param);

            var list = this.BaseRepository().FindList(expression).Result;

            List<goodscar> result = new List<goodscar>();   

            foreach (var item in list)
            {
                goodscar dto = new goodscar();
                dto.pw_id = item.Id.Value;
                dto.VINName = item.VIN+"["+item.name+"]";

                result.Add(dto);
            }
            return result;
        }

        public async Task<List<GoodsWarehouseEntity>> GetPageList(GoodsWarehouseListParam param, Pagination pagination)
        {
            StringBuilder strSql = new StringBuilder();
            var parameter = new List<DbParameter>();
            strSql.Append(@"SELECT a.*,b.goods_name FROM goods_warehouse  a JOIN
            goods_info b ON a.goods_id=b.Id and a.status=0 ");

            if (param.goodsid.IsNullOrZero())
            {
                if (!param.goods_name.IsEmpty())
                {
                    strSql.Append(" AND b.goods_name like @goods_name ");
                    parameter.Add(DbParameterExtension.CreateDbParameter("@goodsname", '%' + param.goods_name + '%'));
                }
            }
            else
            {
                strSql.Append(" AND a.goods_id=@goods_id ");
                parameter.Add(DbParameterExtension.CreateDbParameter("@goods_id", param.goodsid));
            }

            if (!param.name.IsEmpty())
            {
                strSql.Append(" AND a.name like @name ");
                parameter.Add(DbParameterExtension.CreateDbParameter("@name", '%' + param.name + '%'));
            }
            if (!param.color.IsEmpty())
            {
                strSql.Append(" AND a.skuname like @skuname ");
                parameter.Add(DbParameterExtension.CreateDbParameter("@skuname", '%' + param.color + '%'));
            }
            //if (!param.model.IsEmpty())
            //{
            //    strSql.Append(" AND a.model like @model ");
            //    parameter.Add(DbParameterExtension.CreateDbParameter("@model", '%' + param.model + '%'));
            //}
            if (!param.shopid.IsNullOrZero() && param.shopid != -1)
            {
                strSql.Append(" AND a.shop_id=@shopid ");
                parameter.Add(DbParameterExtension.CreateDbParameter("@shopid", param.shopid));
            }
            if (!param.category_id.IsNullOrZero() && param.category_id != -1)
            {
                strSql.Append(" AND a.category_id=@category_id ");
                parameter.Add(DbParameterExtension.CreateDbParameter("@category_id", param.category_id));
            }
            if (!param.goods_model_id.IsNullOrZero() && param.goods_model_id != -1)
            {
                strSql.Append(" AND a.goods_model_id=@goods_model_id ");
                parameter.Add(DbParameterExtension.CreateDbParameter("@goods_model_id", param.goods_model_id));
            }
            if (!param.tenant_id.IsNullOrZero())
            {
                strSql.Append(" AND a.tenant_id=@tenant_id ");
                parameter.Add(DbParameterExtension.CreateDbParameter("@tenant_id", param.tenant_id));
            }


            IEnumerable<GoodsWarehouseEntity> list = await this.BaseRepository().FindList<GoodsWarehouseEntity>(strSql.ToString(), parameter.ToArray(), pagination);
            return list.ToList();
        }

        public async Task<GoodsWarehouseEntity> GetEntity(long id)
        {
            var data=await this.BaseRepository().FindEntity<GoodsWarehouseEntity>(id);
            //查询品牌
            //查询型号
            var goodsmodel = this.BaseRepository().FindEntity<ModelsEntity>(data.goods_model_id.Value).Result;
            //if (goodsmodel!=null)
            //{
            //    data.rule = goodsmodel.rule;
            //    data.unitdoc = goodsmodel.unit.GetDescriptionByEnum<HireCarUnitEnum>();
            //}
            
            var goods = this.BaseRepository().FindEntity<GoodsEntity>(data.goods_id.Value).Result;
            var brand = this.BaseRepository().FindEntity<BrandInfoEntity>(goods.brand_id.Value).Result;
            data.goods_name = goods.goods_name;

            if (brand!=null) {
                data.brand_name = brand.brand_name;
            }

            return data;
        }

        public int GetVINEntity(GoodsWarehouseEntity entity)
        {
            return this.BaseRepository().FindList<GoodsWarehouseEntity>(t => t.VIN==entity.VIN && t.Id != entity.Id).Result.Count();
        }
        #endregion

        #region 提交数据
        public async Task SaveForm(GoodsWarehouseEntity entity)
        {
            //获取商品信息
            var goods=this.BaseRepository().FindEntity<GoodsEntity>(entity.goods_id.Value).Result;
            if (goods!=null)
            {
                entity.goods_model_id = goods.goods_model_id;
                entity.goods_model_name = goods.goods_model;
                entity.goods_name = goods.goods_name;
                entity.goods_id = goods.Id;
                entity.category_id = goods.category_id;
                entity.category_name = goods.category_name;
                entity.goods_type = goods.goods_type;
                entity.shop_id = goods.shop_id;
                entity.rule = goods.price;
                entity.tenant_id = goods.tenant_id;//添加到那个门店就是那个会员信息
            }
            entity.status = 0;
            if (entity.Id.IsNullOrZero())
            {
                //entity.current_cnt = entity.in_cnt;
                entity.current_cnt =1;
                entity.Create();
                await this.BaseRepository().Insert(entity);
                GoodsStorageRecordEntity goodsStorage = new GoodsStorageRecordEntity();
                goodsStorage.Create();
                goodsStorage.goodsId = entity.goods_id;
                goodsStorage.productId = entity.Id;
                goodsStorage.createtime = DateTime.Now;
                goodsStorage.storageCount =1;
                goodsStorage.tenant_id = goods.tenant_id;
                goodsStorage.createtime=DateTime.Now;
                await this.BaseRepository().Insert<GoodsStorageRecordEntity>(goodsStorage);
            }
            else
            {
                
                await this.BaseRepository().Update(entity);
            }
        }

        public async Task DeleteForm(string ids)
        {
            long[] idArr = TextHelper.SplitToArray<long>(ids, ',');

            //foreach (var item in idArr)
            //{
            //    var pw=GetEntity(item).Result;
            //    //增加颜色的库存
            //    var color = this.BaseRepository().FindList<GoodsAttrEntity>(t => t.Id == pw.colorid).Result.FirstOrDefault();
            //    color.count = color.count -1;
            //    await this.BaseRepository().Update(color);
            //}
            await this.BaseRepository().Delete<GoodsWarehouseEntity>(idArr);
        }
        #endregion

        #region 私有方法
        private Expression<Func<GoodsWarehouseEntity, bool>> ListFilter(GoodsWarehouseListParam param)
        {
            var expression = LinqExtensions.True<GoodsWarehouseEntity>();
            if (param != null)
            {
                if (!param.tenant_id.IsNullOrZero())
                {
                    expression = expression.And(t => t.tenant_id == param.tenant_id);
                }
                if (!param.shopid.IsNullOrZero() && param.shopid!=-1)
                {
                    expression = expression.And(t => t.shop_id == param.shopid);
                }
                if (!param.colorid.IsNullOrZero())
                {
                    expression = expression.And(t => t.colorid == param.colorid);
                }
                if (!param.skuid.IsNullOrZero())
                {
                    expression = expression.And(t => t.skuid == param.skuid);
                }
            }
            return expression;
        }
        #endregion
    }
}
